﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;
using Enterprise.Templates;
using System.Data.SqlClient;
using System.Web;

namespace Enterprise.Controls
{
    public abstract class MasterBase : MasterPage
    {
        protected RegionPanel template;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
             /*
              This function loads a PageTemplate. 
              If no template is specified, it will try load it from "Template/skinName" directory.
              If template dir is empty it will load the default template "Templates/Template.ascx"
             */

            //Add cache later
            SqlConnection Conn = new SqlConnection(Config.ConnectionString());
            try
            {
                SqlCommand command = new SqlCommand(string.Format("SELECT * FROM SiteMap WHERE ID={0}", Convert.ToInt32(Request["PageID"])), Conn);
                Conn.Open();
                SqlDataReader dr = command.ExecuteReader();

                if (dr.Read() && (Request["PageID"] != null))
                {
                    template.TemplateFile = string.Format("~/App_Data/Templates/{0}/{1}", Page.Theme, Convert.ToString(dr["PageTemplate"]));
                    return;
                }
                else
                {
                    string[] templates = Directory.GetFiles(Server.MapPath(string.Format("~/App_Data/Templates/{0}/", Page.Theme)));

                    if (templates != null || templates.Length > 0)
                    {
                        if (templates.Length == 1)
                            template.TemplateFile = string.Format("~/App_Data/Templates/{0}/{1}", Page.Theme, templates[0].Substring(templates[0].LastIndexOf("\\") + 1));
                    }
                    else
                    {
                        template.TemplateFile = "~/App_Data/Templates/Template.ascx";
                    }
                }

            }
            finally { Conn.Close(); }

        }
    }
}
